<template>
	<view>
		<view class="uni-common-mt">
			<view class="uni-form-item uni-column">
				<uni-data-select
				  v-model="prefixValue"
				  :localdata="prefixRange"
				  @change="prefixChange"
				></uni-data-select>
				<input class="inputText" style="width:700rpx;height:76rpx;" v-model="writeContent" placeholder="请输入桶号" />
				<button type="primary" size="default" @click="writeRFID">写入桶号</button>
				<view style="height:200rpx;display: flex;">
					<text style="text-align: center; justify-content: center;align-items: center;">{{rfid}}</text>
				</view>
				<button type="warn" size="default" @click="readRFID">读取桶号</button>
			</view>
		</view>
	</view>
</template>

<script>
	var uhfSDK = uni.requireNativePlugin("UHFSDK");
	const modal = uni.requireNativePlugin('modal');
	export default {
		onLoad(){
			var ret = uhfSDK.initUHF();
			if(ret.code != "0"){
				modal.toast({
					message: '初始化失败！',
					duration: 1.5
				});
				return;
			}
		},
		created(){
			var that = this;
			//注册全局变量用于接收后台程序主动发起的数据并且记录最后一次盘点的卡数据用来测试读卡
			plus.globalEvent.addEventListener('sendMessage', function(e){
				if(e.tag == "inventory"){
					that.cardInfo = JSON.parse(e.msg);
					if(that.rfids.length >= 5){
						that.rfids.shift();
						that.rfids.push(that.cardInfo.epc);
					}else{
						that.rfids.push(that.cardInfo.epc);
					}
					
				}else if(e.tag == "read"){
					that.readInfo = JSON.parse(e.msg);
				}else if(e.tag = "write"){
					that.writeInfo = JSON.parse(e.msg);
				}	
			});
			// plus.key.addEventListener('keydown', function(event){
			// 	console.log(event.keyCode);
			// });
		},
		data() {
			return {
				prefixValue: 0,
				prefixRange: [
					{ value: 0, text: "纯数字" },
					{ value: 1, text: "DJY-III" },
					{ value: 2, text: "DJY-II" },
				],
				writeContent: '',
				tempContent: '',
				rfid: '',
				cardInfo:{"epc":"123123123"},
				writePassword:"00000000",
				rfids: [],
			}
		},
		methods: {
			playAudio(type){
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				if(type == 'readStart'){
					innerAudioContext.src = "/storage/emulated/0/Android/data/uni.UNIA6719C4/apps/__UNI__A6719C4/www/static/audio/readStart.mp3";
				}else if(type == 'readEnd'){
					innerAudioContext.src = "/storage/emulated/0/Android/data/uni.UNIA6719C4/apps/__UNI__A6719C4/www/static/audio/readEnd.mp3";
				}else if(type == 'writeStart'){
					innerAudioContext.src = "/storage/emulated/0/Android/data/uni.UNIA6719C4/apps/__UNI__A6719C4/www/static/audio/writeStart.mp3";
				}else if(type == 'writeEnd'){
					innerAudioContext.src = "/storage/emulated/0/Android/data/uni.UNIA6719C4/apps/__UNI__A6719C4/www/static/audio/writeEnd.mp3";
				}
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
			},
			prefixChange(){
				this.writeContent = '';
			},
			stopInventory(){
				uhfSDK.inventoryStop();
			},
			startInventory(){
				this.rfids.length = 0;
				uhfSDK.inventoryStart();
			},
			openDev(){
				var ret = uhfSDK.openDev();
				if(ret.code != "0"){
					modal.toast({
						message: '初始化失败！',
						duration: 1.5
					});
					return;
				}
			},
			closeDev(){
				uhfSDK.closeDev();
			},
			readRFID(){
				this.rfid = '';
				this.playAudio('readStart');
				uni.showLoading({
					title: '正在读取，请稍候...',
					mask: true,
				});
				this.openDev();
				this.startInventory();
				setTimeout(this.readCallback(), 3000);
			},
			readCallback(){
				this.rfids.sort();
				if(this.rfids.length >= 5 && this.refids[0] == this.refids[4]){
					var ret = uhfSDK.selectCard({
						"epcStr":this.refids[4],
						"mFlag":true
					});
					if(ret.code == 0) {
						var result = uhfSDK.readArea({
							'area':1,
							'count':10,
							'password':this.writePassword,
							'addr':2,
						})
						uni.hideLoading(); // 连接成功后隐藏加载提示
						if(result != 'success')
						{
							modal.toast({
								message: '读卡失败，请靠近RFID后重试',
								duration: 1.5
							});
							this.rfid = '读取失败！';
						}
						else{
							uhfSDK.selectCard({
								"epcStr":"",
								"mFlag":false
							});
							modal.toast({
								message: this.rfid,
								duration: 1.5
							});
							this.rfid = this.hexCharCodeToStr(this.refids[4]);
							this.playAudio('readEnd');
						}
						this.stopInventory();
						this.closeDev();
					}else{
						uni.hideLoading(); // 连接成功后隐藏加载提示
						modal.toast({
							message: "读取失败！",
							duration: 1.5
						});
						this.rfid = '读取失败！';
						this.stopInventory();
						this.closeDev();
					}
				}else{
					setTimeout(this.readCallback(), 1000)
				}
			},
			writeRFID(){
				this.rfid = '';
				this.playAudio('writeStart');
				uni.showLoading({
					title: '正在写入，请稍候...',
					mask: true,
				});
				this.openDev();
				this.startInventory();
				setTimeout(this.writeCallback(), 3000);
			},
			writeCallback(){
				this.rfids.sort();
				if(this.rfids.length >= 5 && this.refids[0] == this.refids[4]){
					var ret = uhfSDK.selectCard({
						"epcStr":this.refids[4],
						"mFlag":true
					});
					if(ret.code == 0) {
						var strs = [];
						strs.push("24");
						if(this.prefixValue == 0){
							this.tempContent = this.writeContent;
						}else if(this.prefixValue == 1){
							this.tempContent = 'DJY-III'+this.writeContent;
						}else{
							this.tempContent = 'DJY-II'+this.writeContent;
						}
						let realLength = this.tempContent.length * 2;
						
						strs.push(this.tempContent);
						let t = this.strToHexCharCode(realLength, strs.join(""));
						
						var result = uhfSDK.writeArea({
							'area':1,
							'content':t.toString().toUpperCase(),
							'password':this.writePassword,
							'addr':1,
						});
						uni.hideLoading(); // 连接成功后隐藏加载提示
						if(result != 'success')
						{
							modal.toast({
								message: '写卡失败！',
								duration: 1.5
							});
							this.rfid = "写卡失败！";
						}else{
							uhfSDK.selectCard({
								"epcStr":"",
								"mFlag":false
							});
							this.rfid = "写入成功，桶号："+this.tempContent+"，请点击读取再次验证！";
							this.playAudio('readEnd');
						}
						this.stopInventory();
						this.closeDev();
					}else{
						uni.hideLoading(); // 连接成功后隐藏加载提示
						modal.toast({
							message: "写卡失败:" + ret.code,
							duration: 1.5
						});
						this.rfid = "写卡失败:" + ret.code;
						this.stopInventory();
						this.closeDev();
					}
				}else{
					setTimeout(this.writeCallback(), 1000)
				}
			},
			strToHexCharCode(realLength, str){
				if (str === "") {
					return "";
				} else {
					var hexCharCode = [];
					for (var i = 0; i < str.length; i++) {
						hexCharCode.push((str.charCodeAt(i)).toString(16));
					}
					let zeroFillLength = 24 - realLength;
					for(var i=0;i<zeroFillLength;i++){
						hexCharCode.push(0);
					}
					return hexCharCode.join("");
				}
			},
			hexCharCodeToStr(hexCharCodeStr){
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					modal.toast({
						message: "存在非法字符！",
						duration: 1.5
					});
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			}
		}
	}
</script>

<style>
	.inputText{
	    min-height: 76rpx;
	    border: 0rpx solid #dadbde;
	    font-size: 36rpx;
	    padding-left: 20rpx;
		padding-right: 20rpx;
	    border-radius: 8rpx;
	    margin-left: 25rpx;
		margin-right: 25rpx;
	    margin-top: 20rpx;
	}
</style>
